package com.renwen.sms.controller;


import com.renwen.sms.util.FileUtil;
import com.renwen.sms.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;


/**
 * 文件管理
 *
 * @author zuo
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileChangeController {
    /**
     * word转Excel
     *
     * @param file 上传的文件
     * @return 转换结果
     */
    @PostMapping("/upload")
    public Result fileUpload(MultipartFile file) {
        try {
            log.info("得到文件：{}", file.getOriginalFilename());
            FileUtil.multipartFileToFile(file);
            return new Result(200, "文件上传成功！");
        } catch (Exception e) {
            log.error("文件上传失败,错误：{}", e.getMessage());
            return new Result(400, e.getMessage() + "");
        }
    }




    @GetMapping("/downloadFile")
    public ResponseEntity<FileSystemResource> downloadWord() {
        return export(new File("file/word_moban.docx"));
    }








    /**
     * 返回下载的文件到浏览器
     * @param file 文件信息
     * @return 返回下载文件
     */
    public ResponseEntity<FileSystemResource> export(File file) {
        if (file == null) {
            return null;
        }
        log.info("获取到文件{},写入浏览器",file);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        try {
            headers.add("Content-Disposition", "attachment; filename=" + URLEncoder.encode(file.getName(),"utf-8").replace("\\+","20%"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Last-Modified", new Date().toString());
        headers.add("ETag", String.valueOf(System.currentTimeMillis()));
        return ResponseEntity.ok().headers(headers).contentLength(file.length()).contentType(MediaType.parseMediaType("application/octet-stream;charset=utf-8")).body(new FileSystemResource(file));

    }
}
